﻿using System;
using System.Threading.Tasks;
using log4net;
using MaximServices.Common;
using MaximServices.Services;
using Quartz;
using Quartz.Logging;
using Autofac;
using MaximServices.Model;

namespace MaximJob
{
    public class SimpleJob : IJob
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(SimpleJob));

        private MottoCheckServices _mottoCheckServices;
        private MockCacheServices _mockCacheServices;
        public SimpleJob()
        {
        }

        public virtual Task Execute(IJobExecutionContext context)
        {
            //JobKey jobKey = context.JobDetail.Key;
            log.Info("自动匹配词条任务开始执行...");

            var mockCache = new MockCache()
            {
                CacheKey = $"key:lock_motto_job",
                CacheValue = DateTime.Now.ToString(),
                CreateTime = DateTime.Now,
                Id = IdFactory.NextId
            };

            using (var scope = ServiceLocator.Instance.BeginLifetimeScope())
            {
                _mottoCheckServices = scope.Resolve<MottoCheckServices>();
                _mockCacheServices = scope.Resolve<MockCacheServices>();

                if (_mockCacheServices.FindCache(mockCache.CacheKey) != null)
                {
                    log.Info("任务正在执行中...");
                }
                else
                {
                    //获取词条
                    _mockCacheServices.LockByCache(() =>
                    {
                        _mottoCheckServices.AutoMatchBaike();

                        return true;

                    }, mockCache, 10000, false);
                }
            }

            return Task.CompletedTask;
        }
    }
}